﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TrayCheckControl
{
    class LogFileSave
    {
        private readonly string dateTimeFormat = "yyyyMMdd HH:mm:ss  >>  ";
        private readonly StringBuilder logData = new StringBuilder(1024);
        //private readonly StringBuilder logDataBuffer = new StringBuilder(1024);
        private readonly string directory = System.DateTime.Now.ToString("yyyyMM");
        private string fileName = System.DateTime.Now.ToString("yyyyMMdd");
        bool writing = false;
        public void AddToLog(string logData)
        {
            if (System.DateTime.Now.ToString("yyyyMMdd") != fileName)
            {
                this.SaveToFile();
                this.fileName = System.DateTime.Now.ToString("yyyyMMdd");
            }
            this.logData.Append($"{System.DateTime.Now.ToString(dateTimeFormat)}{logData}\r");
            if (this.logData.Length >= 1024)
            {
                this.SaveToFile();
            }
        }
        private void SaveToFile()
        {
            System.IO.FileInfo fi = new System.IO.FileInfo($"Logs/{directory}/{fileName}.txt");
            if(!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            if(!fi.Exists)
            {
                fi.Create().Close();
            }
            if (!writing)
            {
                writing = true;
                string tmp = logData.ToString();
                try
                {
                    System.IO.File.AppendAllText(fi.FullName, tmp);
                    lock (logData)
                    {
                        logData.Remove(0, tmp.Length);
                        writing = false;
                    }
                }
                catch
                {

                }
            }
        }
        //private void CheckDirectory()
        //{
        //    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(this.directory);
        //    if(!di.Exists)
        //    {
        //        di.Create();
        //    }
        //}
        public void Close()
        {
            this.SaveToFile();
        }
    }
}
